package cn.imvc.app.jobs;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.entities.Orders;
import cn.imvc.app.models.DealerModel;
import cn.imvc.app.models.GoodsOrderModel;
import cn.imvc.app.models.OrdersModel;
@DisallowConcurrentExecution
public class AutomaticOrdersFinishQuarz {

	private static final Logger log = Logger.getLogger(AutomaticOrdersFinishQuarz.class);
	@Autowired
	private OrdersModel ordersModel;
	@Autowired
	private GoodsOrderModel goodsOrderModel;

	/**
	 * 一级订单, 完成状态确定//累计消费满1000元。。。自动升级为分销商
	 */

	public void automaticOrdersFinish(JobExecutionContext context) {
		Calendar calendar = Calendar.getInstance();// 日历对象
		calendar.add(Calendar.DAY_OF_MONTH, -7);
		List<Orders> ordersList = ordersModel.findByStateAndCreatedAtLessThan(OrderState.Delivery.getValue(),calendar.getTime());
		for (Orders order : ordersList) {
			try {
				boolean flag = true;
				List<GoodsOrder> goodsOrderList1 = goodsOrderModel.findByOrder(order);
				for (GoodsOrder goodsOrder : goodsOrderList1) {
					byte state = goodsOrder.getState();
					if (state != OrderState.Reject.getValue() && state != OrderState.RefundSuccess.getValue() && state != OrderState.RefundFailed.getValue() && state != OrderState.Finish.getValue()) {
						flag = false;
						break;
					}
				}
				if (flag) {
					log.info("1级订单id:::"+order.getId()+"判断成功。");
					order.setState(OrderState.Finish.getValue());
					order.setUpdatedAt(new Date());
					order.setFinishTime(new Date());
					ordersModel.update(order);
				}
			} catch (Exception e) {
				log.error(e.toString());
			}
		}
		System.out.println("一级订单状态更新完成！！！(自动升级分销商)");

	}
}
